#include "system/socket/Connection.hpp"
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <string.h>

namespace SystemSocket
{
	std::string Connection::read()
	{
		char aBuffer[1];

		std::string aWhatWasRead;
		do
		{
			bzero(aBuffer, 1);
			if(recv(_activeSockedFd, aBuffer, 1, 0) > 0)
			{
				aWhatWasRead.push_back(aBuffer[0]);
			}
			else throw ReadException();

		}
		while(aBuffer[0] != 0x0A);

		return aWhatWasRead;
	}

	Connection::~Connection()
	{
		if(_activeSockedFd > 0)
			::close(_activeSockedFd);
	}
	 void Connection::write(std::string iInput)
	 {
		 int aNumber = ::write(_activeSockedFd, iInput.c_str(), iInput.size());
		 if(aNumber <= 0)
			 throw WriteException();
	 }

	 void Connection::close()
	 {
		 // close the connection
		 ::close(_activeSockedFd);
		 // mark the connection was closed
		 _activeSockedFd = -1;
	 }

	 bool Connection::isValid()
	 {
		// if the connections was already closed then is invalid
		if(_activeSockedFd == -1 || _forceInvalid)
			return false;
		return true;
	 }

};
